﻿using AutoMapper;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using QMERP.Domain.Dtos;
using QMERP.Domain.Entities;
using QMERP.Infrastructure.EFCore;
using QMERP.Infrastructure.EFCore.Extensions;

namespace QMERP.Application.Services
{
    public class LogSignInService : ILogSignInService
    {
        private readonly IMapper _mapper;
        private readonly IHttpContextAccessor _context;
        private readonly QMERPDbContext _db;
        public LogSignInService(IHttpContextAccessor context, QMERPDbContext db, IMapper mapper)
        {
            _context = context;
            _mapper = mapper;
            _db = db;
            _mapper = mapper;
        }
        /// <summary>
        /// 获取登录日志列表
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public async Task<PageResponse<LogSignInResponse>> Query(PageRequest info)
        {
            PageResponse<LogSignInResponse> model = new PageResponse<LogSignInResponse>();
            var query = _db.LogSignIn.OrderByDescending(x => x.SignInOn);
            int totalCount = await query.CountAsync();
            List<LogSignIn> list = await query.Paging(info.PageIndex, info.PageSize).ToListAsync();
            model.PageIndex = info.PageIndex;
            model.PageSize = info.PageSize;
            model.TotalCount = totalCount;
            model.List = _mapper.Map<List<LogSignInResponse>>(list);
            return model;
        }
        /// <summary>
        /// 记录登录日志
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task Add(LogSignInAddRequest request)
        {
            var logSignIn = _mapper.Map<LogSignIn>(request);
            await _db.AddAsync(logSignIn);
            await _db.SaveChangesAsync();
        }
    }
}
